import { ref } from 'vue';
import { checkVisitor } from '@/common/api/user.js';
export default function() {
	const uniIdCo = uniCloud.importObject("uni-id-co", { customUI: true });
	const visitorBtnLoading = ref(false);
	// 游客登录逻辑：给用户创建一个有账账号密码的账户
	async function visitorLogin(redirectTo) {
		visitorBtnLoading.value = true;
		const params = {
			username: `visitor_${getApp().globalData.deviceId}`,
			password: '123456', //游客初始化密码
			captcha: ''
		}
		const { data } = await checkVisitor({
			username: params.username
		})
		if (data._id) { //该游客用户存在，直接进行登录
			login(params, data, redirectTo);
		} else { //该游客用户不存在，直接注册登录
			uniIdCo.registerUser(params).then(e => {
				getApp().loginSuccess({
					...e,
					showToast: false
				});
				redirectTo(true);
			}).catch(e => {
				getApp().globalData.notify({
					type: 'error',
					message: e.message
				})
			}).finally(() => {
				visitorBtnLoading.value = false;
			})
		}
	}
	// 登录
	function login(params, data, redirectTo) {
		uniIdCo.login({
			username: params.username,
			password: data.pwd || params.password,
			captcha: params.captcha
		}).then(e => {
			getApp().loginSuccess({
				...e,
				showToast: false
			});
			redirectTo(true);
		}).catch(e => {
			if (e.errCode == 'uni-id-captcha-required') {
				uni.$emit('captcha-popup-valid', {
					scene: 'login-by-pwd',
					callback(captcha) {
						params.captcha = captcha;
						login(params, data, redirectTo);
					}
				})
			} else {
				getApp().globalData.notify({
					type: 'error',
					message: e.message
				})
			}
		}).finally(() => {
			params.captcha = '';
			visitorBtnLoading.value = false;
		})
	}
	return {
		visitorLogin,
		visitorBtnLoading
	}
}